package com.dylovedz.javafxphone.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.dylovedz.javafxphone.domain.LastOpenFile;
import com.dylovedz.javafxphone.service.LastOpenFileService;
import com.dylovedz.javafxphone.service.PhoneExportTask;
import com.dylovedz.javafxphone.util.PhoneUtil;
import com.google.i18n.phonenumbers.NumberParseException;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * 主界面控制器
 *
 * @author dylovedz
 * @date 2023/03/09 16:50
 */
@Slf4j
@FXMLController
public class PhoneController implements Initializable {


    @Resource
    LastOpenFileService lastOpenFileService;

    // 主容器
    public Pane rootPane;

    public ProgressBar exportPro;
    public Button btnChooseFile;
    public Button btnSearch;
    public TextField phoneText;
    public TextArea phoneGeoText;
    public Tooltip btnChooseFileTip;
    public Button btnChooseDir;
    public Tooltip btnChooseDirTip;
    public Button btnExport;

    private String inFile;
    private String outDir;
    private File lastFile;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        LastOpenFile lastPath = lastOpenFileService.findById(1);
        if (lastPath.getLastPath() != null) {
            lastFile = FileUtil.file(lastPath.getLastPath());
        }
        log.info("initialize: {}", location.getPath());
    }

    /**
     * 弹出框按钮单击事件
     * @param actionEvent
     */
    public void onBtnAlertClick(ActionEvent actionEvent) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setContentText("当前时间：" + DateUtil.now());
        alert.show();
    }

    /**
     * 选择文件按钮单机事件
     * @param actionEvent
     */
    public void onBtnChooseFileClick(ActionEvent actionEvent) {
        Window window = rootPane.getScene().getWindow();
        FileChooser fileChooser = new FileChooser();
        // 文件类型过滤器
        FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Excel files (*.xls, *.xlsx)", "*.xls", "*.xlsx");
        fileChooser.getExtensionFilters().add(filter);
        if (ObjectUtil.isNotNull(lastFile) && FileUtil.isDirectory(lastFile)) {
            fileChooser.setInitialDirectory(lastFile);
        }

        // ...
        File file = fileChooser.showOpenDialog(window);
        String fileName = file == null ? "" : file.getName();
        String fileAbsolutePath = file == null ? "" : file.getAbsolutePath();

        if (file != null) {
            btnChooseFile.setText(fileAbsolutePath);
            btnChooseFileTip.setText(fileAbsolutePath);
            inFile = fileAbsolutePath;
            lastFile = FileUtil.file(file.getParent());
            lastOpenFileService.saveOrUpdateById(1, file.getParent());
            /*Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("文件路径：" + fileAbsolutePath);
            alert.show();*/
        }
    }

    /**
     * 查询手机号归属地
     * @param actionEvent
     */
    public void onBtnSearchClick(ActionEvent actionEvent) throws NumberParseException {
        String phoneNumber = phoneText.getText();
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        if (StrUtil.isBlank(phoneNumber)) {
            alert.setContentText("请输入手机号");
            alert.show();
            return;
        }
        // 是否为正确格式
        if (!PhoneUtil.isValid(phoneNumber)) {
            alert.setContentText("请输入正确的手机号");
            alert.show();
            return;
        }
        String geo = PhoneUtil.getGeo(phoneNumber);
        if (ObjectUtil.equals(geo, "中国") || ObjectUtil.isEmpty(geo)) {
            Map<String, String> phoneGeo = PhoneUtil.getPhoneByHttp(phoneNumber);
            geo = phoneGeo.get("carrier") + " " +phoneGeo.get("geo");
        } else {
            geo = PhoneUtil.getCarrier(phoneNumber) + " " + geo;
        }

        phoneGeoText.setText(geo);
    }

    /**
     * 选择导出目录
     * @param actionEvent
     */
    public void onBtnChooseDirClick(ActionEvent actionEvent) {
        Window window = rootPane.getScene().getWindow();
        DirectoryChooser folderChooser = new DirectoryChooser();
        if (ObjectUtil.isNotNull(lastFile)  && FileUtil.isDirectory(lastFile)) {
            folderChooser.setInitialDirectory(lastFile);
        }
        // ...
        File file = folderChooser.showDialog(window);
        String fileName = file == null ? "" : file.getName();
        String fileAbsolutePath = file == null ? "" : file.getAbsolutePath();
        if (file != null) {
            btnChooseDir.setText(fileAbsolutePath);
            btnChooseDirTip.setText(fileAbsolutePath);
            outDir = fileAbsolutePath;
            lastFile = file;
            lastOpenFileService.saveOrUpdateById(1, fileAbsolutePath);
            /*Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("文件路径：" + fileAbsolutePath);
            alert.show();*/
        }
    }

    /**
     * 导出逻辑处理
     * @param actionEvent
     * @throws IOException
     * @throws NumberParseException
     */
    public void onBtnExportClick(ActionEvent actionEvent) throws IOException, NumberParseException {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        if (StrUtil.isBlank(inFile)) {
            alert.setContentText("请选择查询的excel");
            alert.show();
            return;
        }
        if (StrUtil.isBlank(outDir)) {
            alert.setContentText("请选择导出目录");
            alert.show();
            return;
        }
        PhoneExportTask phoneExportTask = new PhoneExportTask(inFile, outDir);
        Thread thread = new Thread(phoneExportTask);
        thread.start();
        phoneExportTask.progressProperty().addListener((observable, oldValue, newValue) -> {
            log.info("进度：{}", newValue);
            exportPro.setProgress((Double) newValue);
        });
    }
}
